import math
import tkinter as tk
from tkinter import Label, Button, filedialog
from openpyxl import Workbook, load_workbook
import re
import os
import sys


def poav_calc(theta12, theta23, theta31):

    temp11 = math.cos(theta12*math.pi/180)
    temp12 = math.cos(theta23*math.pi/180)
    temp13 = math.cos(theta31*math.pi/180)
    temp14 = math.sin(theta12*math.pi/180)

    v1_1 = -1
    v2_1 = -temp11
    v2_2 = temp14
    v3_1 = -temp13
    v3_2 = (temp12 - temp11*temp13)/temp14
    v3_3 = math.sqrt(1-v3_1**2-v3_2**2)

    N = v1_1*v2_2*v3_3
    D1 = (v2_2*v3_3)**2
    D2 = ((v2_1-v1_1)*v3_3)**2
    D3 = ((v2_1-v1_1)*v3_2 - (v3_1-v1_1)*v2_2)**2

    temp30 = N / math.sqrt(D1 + D2 + D3)
    temp31 = -temp30

    temp35 = math.acos(temp30)*180/math.pi
    temp36 = math.acos(temp31)*180/math.pi

    return round(temp35-90, 8)

def read_txt(file_path="poav.txt"):
    target_file_path = re.sub(r'\.txt$', '_result.txt', file_path)
    with open(file_path, 'r', encoding='utf-8') as source_file:
        with open(target_file_path, 'w', encoding='utf-8') as target_file:
            for line in source_file:
                params = list(map(float,line.split(" ")))
                res = poav_calc(params[0], params[1], params[2])
                target_file.write(line.strip() + " " + str(res) + "\n")
            text_label.config(text="计算结束！\n结果保存在"+target_file_path)

def read_excel(file_path="poav.xlsx"):
    target_file_path = re.sub(r'\.xlsx$', '_result.xlsx', file_path)
    source_wb = load_workbook(file_path)
    source_sheet = source_wb.active
    target_wb = Workbook()
    target_sheet = target_wb.active
    for source_row in source_sheet.iter_rows(min_row=1, values_only=True):
        res = poav_calc(source_row[0], source_row[1], source_row[2])
        target_row = source_row + (res,)
        target_sheet.append(target_row)
    target_wb.save(target_file_path)
    text_label.config(text="计算结束！\n结果保存在" + target_file_path)


def center_window(window, width=400, height=500):
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    x = (screen_width - width) // 2
    y = (screen_height - height) // 2
    window.geometry(f"{width}x{height}+{x}+{y}")

def upload_file():
    file_path = filedialog.askopenfilename(filetypes=[("Data Files", "*.txt;*.xlsx")])
    if file_path:
        text_label.config(text=f"已上传: {file_path.split('/')[-1]}，正在计算中...")
        ext = file_path.split(".")[-1].lower()
        if ext == "txt":
            read_txt(file_path)
        elif ext == "xls" or "xlsx":
            read_excel(file_path)
def resource_path(relative_path):
    """ 获取打包后可执行文件的资源路径 """
    if hasattr(sys, "_MEIPASS"):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.abspath(relative_path)

# 创建主窗口
root = tk.Tk()
root.title("Pi Orbital Axis Vector Analysis")
root.iconbitmap(resource_path("icon.ico"))
center_window(root, 550, 300)


# 设置 grid 行列权重，使组件居中
root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)
root.grid_rowconfigure(2, weight=1)
root.grid_columnconfigure(0, weight=1)

# 创建文本显示区域
text_label = Label(root, text="请上传数据文件!", font=("Arial", 12))
text_label.grid(row=3, column=0, pady=20, sticky="n")

# 创建按钮
btn = Button(root, text="上传", command=upload_file, font=("Arial", 12, "bold"), fg="white", bg="#007BFF", padx=20, pady=10, borderwidth=2, relief="raised")
btn.grid(row=4, column=0, pady=30, sticky="s")

# 进入主事件循环
root.mainloop()

#if __name__ == '__main__':
#    createWindow()
# poav_calc(120, 120, 108)
